import React from 'react';
import type { TransactionRead, TransactionSplit, AccountRead } from '../types';
import Card from './ui/Card';

interface TransactionItemProps {
  split: TransactionSplit;
  style: React.CSSProperties;
  onClick: () => void;
  currencySymbol: string;
}

const TransactionItem: React.FC<TransactionItemProps> = ({ split, style, onClick, currencySymbol }) => {
  const isExpense = split.type === 'withdrawal';
  const amount = parseFloat(split.amount);
  const formattedAmount = new Intl.NumberFormat('zh-CN', {
    style: 'decimal',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(amount);

  const formattedDate = new Date(split.date).toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
  });

  return (
    <Card 
        style={style} 
        onClick={onClick}
        className="flex items-center space-x-4 transition-all opacity-0 animate-fade-in-up cursor-pointer hover:bg-slate-700/60"
    >
      <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${isExpense ? 'bg-red-500/20 text-red-400' : 'bg-green-500/20 text-green-400'}`}>
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-6 h-6">
          {isExpense 
            ? <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m0 0l6.75-6.75M12 19.5l-6.75-6.75" />
            : <path strokeLinecap="round" strokeLinejoin="round" d="M12 19.5v-15m0 0l-6.75 6.75M12 4.5l6.75 6.75" />
          }
        </svg>
      </div>
      <div className="flex-1 overflow-hidden">
        <p className="font-semibold text-slate-100 truncate">{split.description}</p>
        <p className="text-sm text-slate-400 truncate">{split.category_name || (isExpense ? split.destination_name : split.source_name)}</p>
        {split.tags && split.tags.length > 0 && (
            <div className="flex flex-wrap gap-1 mt-2">
                {split.tags.map((tag, i) => (
                    <span key={i} className="px-2 py-0.5 text-xs bg-slate-700 text-slate-300 rounded-full">{tag}</span>
                ))}
            </div>
        )}
      </div>
      <div className="text-right">
        <p className={`font-bold ${isExpense ? 'text-red-400' : 'text-green-400'}`}>
          {isExpense ? '-' : '+'} {currencySymbol}{formattedAmount}
        </p>
        <p className="text-sm text-slate-500">{formattedDate}</p>
      </div>
    </Card>
  );
};

interface TransactionListProps {
  transactions: TransactionRead[];
  onTransactionClick: (transaction: TransactionRead) => void;
  accountMap: Map<string, AccountRead>;
}

const TransactionList: React.FC<TransactionListProps> = ({ transactions, onTransactionClick, accountMap }) => {

  const getCurrencySymbol = (split: TransactionSplit) => {
    const accountId = split.source_id || split.destination_id;
    if (accountId && accountMap.has(accountId)) {
      return accountMap.get(accountId)!.attributes.currency_symbol;
    }
    return '¥'; // Fallback
  };

  return (
    <section>
      <h2 className="text-lg font-semibold text-slate-300 mb-3">最近交易</h2>
      <div className="space-y-3">
        {transactions.length > 0 ? (
          transactions.flatMap((tx, txIndex) => tx.attributes.transactions.map((split, splitIndex) => (
            <TransactionItem 
              key={`${tx.id}-${splitIndex}`} 
              split={split} 
              onClick={() => onTransactionClick(tx)}
              currencySymbol={getCurrencySymbol(split)}
              style={{ animationDelay: `${(txIndex * 2 + splitIndex) * 25}ms` }} 
            />
          )))
        ) : (
          <Card className="text-center text-slate-500 py-8">没有找到任何交易记录。</Card>
        )}
      </div>
       <style>{`
        @keyframes fade-in-up {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.5s ease-out forwards;
        }
      `}</style>
    </section>
  );
};

export default TransactionList;